<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:replace="teacher/teacher-common::commonCss(~{::title},~{},~{::script},~{::style})">
    <title>JAVA在线考试-考试管理</title>
    <script th:src="@{/layui/xm-select.js}"></script>
    <script th:src="@{/laydate/laydate.js}"></script>
    <style>
        .body{
            background-color: #f8f8f8;
        }
    </style>

    <script type="text/html" id="toolbar">
        <div class="layui-btn-container">
            <button lay-event="deletes" class="layui-btn layui-btn-danger">删除选中行</button>
            <button lay-event="save" class="layui-btn layui-btn-normal">新增</button>
        </div>
    </script>
    <script type="text/html" id="bar">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a><br/>
    </script>
    <script th:inline="javascript">
        layui.use(['table','element','laydate','form'], function(){
            var table = layui.table;
            var element = layui.element;
            var laydate = layui.laydate;
            var form = layui.form;

            var clazzIds = xmSelect.render({
                el: '#clazzIds'
            })
            laydate.render({
                elem: '#search-createTime'
                ,range: true
            });
            laydate.render({
                elem: '#search-testTime'
                ,range: true
            });
            laydate.render({
                elem: '#examTime'
                ,type: 'datetime'
                ,range: true
            });

            $("#searchBtn").click(function () {
                reload();
            });
            $("#resetBtn").click(function () {
                $("#searchexamInfoForm")[0].reset();
                tableIns.reload({
                    where: {
                        "msg": "",
                        "code": "",
                        "data": {
                            "title": '',
                            "content": '',
                            "state": 0,
                            "examStartTime": '',
                            "examEndTime": '',
                            "createStartTime": '',
                            "createEndTime": ''
                        }
                    }
                    , page: {
                        curr: 1
                    }
                });
            });

            var tableIns = table.render({
                elem: '#examTable'
                , url: '/exam/listForPage'
                , toolbar: '#toolbar'
                , contentType: 'application/json'
                , method: 'post'
                , where: {
                    "msg": "",
                    "code": "",
                    "data": {
                        "title": $('#search-title').val(),
                        "content": $('#search-content').val(),
                        "state": $('#search-state').val(),
                        "examStartTime": $("#search-testTime").val().split(" - ")[0],
                        "examEndTime": $("#search-testTime").val().split(" - ")[1] != null ? $("#search-testTime").val().split(" - ")[1] : "",
                        "createStartTime": $("#search-createTime").val().split(" - ")[0],
                        "createEndTime": $("#search-createTime").val().split(" - ")[1] != null ? $("#search-createTime").val().split(" - ")[1] : ""
                    }
                }
                , defaultToolbar: []
                , page: true
                , limits: [5, 10, 20]
                , limit: 10
                , cols: [
                    [
                        {type: 'checkbox', fixed: 'left'}
                        , {field: 'id', title: 'ID', hide: true}
                        , {field: 'paperId', title: 'paperId', hide: true}
                        , {field: 'title', title: '考试名'}
                        , {field: 'content', title: '描述内容'}
                        , {field: 'paperTitle', title: '试卷'}
                        , {field: 'clazzList', title: '考试班级', width: 175, templet: function (d) {
                            var clazzList = d.clazzList;
                            var select = "";
                            $.each(clazzList,function (index,clazz) {
                                select += "["+clazz.name+"] ";
                            })
                            select += "</select>";
                            return select
                        }}
                        , {field: 'state', title: '状态', templet: function (d) {
                            var state = d.state;
                            if(state===1){
                                return '<span>进行中</span>';
                            }else if(state===2){
                                return '<span>批卷中</span>';
                            }else if(state===3){
                                return '<span>已结束</span>';
                            }else{
                                return '<span>未开始</span>';
                            }
                        }}
                        , {field: 'startTime', title: '开始时间'}
                        , {field: 'endTime', title: '结束时间'}
                        , {field: 'time', title: '用时'}
                        , {field: 'createTime', title: '创建时间'}
                        , {title: '操作', fixed: 'right', width: 135, toolbar: '#bar'}
                    ]
                ]
                ,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
                    return {
                        "code": res.result.code, //解析接口状态
                        "msg": res.message, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.records //解析数据列表
                    };
                }
            });

            //监听工具条
            table.on('tool(examTable)', function (obj) {
                var data = obj.data;
                switch (obj.event) {
                    case 'delete':
                        layer.confirm('真的删除么', function (index) {
                            if(data.state !== 0){
                                layer.msg("考试已经开始，无法修改信息",{icon:'5'});
                                return;
                            }
                            $.ajax({
                                url : '/exam/delete/'+data.id,
                                type : 'post',
                                dataType : 'json',
                                success : function(n) {
                                    if (n.result.status) {
                                        reload();
                                    }else {
                                        layer.msg("删除考试失败,"+n.result.msg);
                                    }
                                },
                                error: function(n) {
                                    layer.msg("删除考试失败,"+n.responseJSON.result.msg);
                                }
                            });
                            layer.close(index);
                        });
                        break;
                    case 'edit':
                        layer.open({
                            type: 1,
                            area: ['700px', '520px'],
                            shadeClose: true, //点击遮罩关闭
                            title: '修改考试信息',
                            btn: ['确定', '取消'],
                            content: $('#examInfoFrame'),
                            success: function (index, layero) {
                                $("#examInfoForm")[0].reset();
                                $("#title").val(data.title);
                                $("#content").val(data.content);
                                $("#time").val(data.time);
                                $("#examTime").val(data.startTime+" - "+data.endTime);

                                $("#paperId").html("");
                                $.ajax({
                                    url: '/paper/list',
                                    type:"get",
                                    dataType:"json",
                                    success:function (data){
                                        if (data.result.status) {
                                            var selectHtml = '';
                                            $.each(data.data,function (i,n){
                                                selectHtml += "<option value='"+n.id+"'>"+n.title+"</option>";
                                            });
                                            $("#paperId").html(selectHtml);
                                        }else {
                                            layer.msg("查询试卷列表失败,"+n.result.msg);
                                        }
                                        form.render(null,"examInfoForm");
                                    }
                                });
                                $("#paperId").val(data.paperId);

                                $.ajax({
                                    url: '/clazz/list',
                                    type:"get",
                                    async:false,
                                    dataType:"json",
                                    success:function (data){
                                        if (data.result.status) {
                                            var text = '[' ;
                                            $.each(data.data,function (i,n){
                                                text +='{ "name":"'+n.name+'" , "value":"'+n.id+'" },';
                                            });
                                            text = text.substr(0, text.length - 1);
                                            text += ']' ;
                                            clazzIds.update({
                                                data: JSON.parse(text)
                                            })
                                        }else {
                                            layer.msg("查询班级列表失败,"+n.result.msg);
                                        }
                                        form.render(null,"examInfoForm");
                                    }
                                });
                                $.ajax({
                                    url: '/clazz/listByExamId/'+data.id,
                                    type:"get",
                                    dataType:"json",
                                    success:function (data){
                                        if (data.result.status) {
                                            var arrayObj = new Array();
                                            $.each(data.data,function (i,n){
                                                arrayObj.push(n.id);
                                            });
                                            clazzIds.setValue(arrayObj)
                                        }else {
                                            layer.msg("查询班级列表失败,"+n.result.msg);
                                        }
                                        form.render(null,"examInfoForm");
                                    }
                                });
                                layui.form.render();
                            },
                            yes: function (index, layero) {
                                if(data.state !== 0){
                                    layer.msg("考试已经开始，无法修改信息",{icon:'5'});
                                    return;
                                }
                                var title = $("#title").val();
                                var content = $("#content").val();
                                var paperId = $("#paperId").val();
                                var time = $("#time").val();
                                var clazzs = clazzIds.getValue('value');
                                var examStartTime = $("#examTime").val().split(" - ")[0];
                                var examEndTime = $("#examTime").val().split(" - ")[1] != null ? $("#examTime").val().split(" - ")[1] : "";

                                if(title==='' || content==='' ){
                                    layer.msg("请输入考试信息",{icon:'5'});
                                    return;
                                }
                                if(paperId===''){
                                    layer.msg("请选择试卷",{icon:'5'});
                                    return;
                                }
                                if(examStartTime==='' || examStartTime==='' ){
                                    layer.msg("请选择考试时间",{icon:'5'});
                                    return;
                                }
                                if(time==='' ){
                                    layer.msg("请输入考试所用时间（分钟）",{icon:'5'});
                                    return;
                                }
                                $.ajax({
                                    url : '/exam/update/'+data.id,
                                    type : 'post',
                                    contentType : 'application/json',
                                    dataType: 'json',
                                    data: JSON.stringify({
                                        "msg":"",
                                        "code":"",
                                        "data": {
                                            "title": title,
                                            "content": content,
                                            "paperId": paperId,
                                            "clazzIds": clazzs,
                                            "time": time,
                                            "examStartTime": examStartTime,
                                            "examEndTime": examEndTime
                                        }
                                    }),
                                    success : function(n) {
                                        if (n.result.status) {
                                            layer.msg("修改考试信息成功");
                                            layer.close(index);
                                            reload();
                                        }else {
                                            layer.msg("修改考试信息失败,"+n.result.msg);
                                        }
                                    },
                                    error: function(n) {
                                        layer.msg("修改考试信息失败,"+n.responseJSON.result.msg);
                                    }
                                });
                            },
                            end: function (res) {
                                $("#examInfoFrame").css("display", 'none');
                            }
                        });
                        break;
                }
                ;
            });
            table.on('toolbar(examTable)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'deletes':
                        var data = checkStatus.data;
                        var size = data.length;
                        console.log(data);
                        if (size != 0) {
                            layer.confirm('真的删除么', function (index) {
                                for (let i = 0; i < size; i++) {
                                    if(data[i].state !== 0){
                                        layer.msg("考试已经开始，无法修改信息",{icon:'5'});
                                        return;
                                    }
                                    $.ajax({
                                        url : '/exam/delete/'+data[i].id,
                                        type : 'post',
                                        dataType : 'json',
                                        success : function(n) {
                                            if (n.result.status) {
                                                reload();
                                            }else {
                                                layer.msg("删除考试失败,"+n.result.msg);
                                            }
                                        },
                                        error: function(n) {
                                            layer.msg("删除考试失败,"+n.responseJSON.result.msg);
                                        }
                                    });
                                }
                                layer.close(index);
                                reload();
                            });
                        } else {
                            layer.msg("请勾选要删除的考试");
                        }
                        break;
                    case 'save':
                        layer.open({
                            type: 1,
                            area: ['700px', '520px'],
                            shadeClose: true, //点击遮罩关闭
                            title: '添加考试',
                            btn: ['确定', '取消'],
                            content: $('#examInfoFrame'),
                            success: function (index, layero) {
                                $("#examInfoForm")[0].reset();
                                $("#paperId").html("");
                                $.ajax({
                                    url: '/paper/list',
                                    type:"get",
                                    dataType:"json",
                                    success:function (data){
                                        if (data.result.status) {
                                            var selectHtml = '';
                                            $.each(data.data,function (i,n){
                                                selectHtml += "<option value='"+n.id+"'>"+n.title+"</option>";
                                            });
                                            $("#paperId").html(selectHtml);
                                        }else {
                                            layer.msg("查询试卷列表失败,"+n.result.msg);
                                        }
                                        form.render(null,"examInfoForm");
                                    }
                                });
                                $.ajax({
                                    url: '/clazz/list',
                                    type:"get",
                                    dataType:"json",
                                    success:function (data){
                                        if (data.result.status) {
                                            var text = '[' ;
                                            $.each(data.data,function (i,n){
                                                text +='{ "name":"'+n.name+'" , "value":"'+n.id+'" },';
                                            });
                                            text = text.substr(0, text.length - 1);
                                            text += ']' ;
                                            clazzIds.update({
                                                data: JSON.parse(text)
                                            })
                                        }else {
                                            layer.msg("查询题库列表失败,"+n.result.msg);
                                        }
                                        form.render(null,"examInfoForm");
                                    }
                                });
                                layui.form.render();
                            },
                            yes: function (index, layero) {
                                var title = $("#title").val();
                                var content = $("#content").val();
                                var clazzs = clazzIds.getValue('value');
                                var paperId = $("#paperId").val();
                                var time = $("#time").val();
                                var examStartTime = $("#examTime").val().split(" - ")[0];
                                var examEndTime = $("#examTime").val().split(" - ")[1] != null ? $("#examTime").val().split(" - ")[1] : "";

                                if(title==='' || content==='' ){
                                    layer.msg("请输入考试信息",{icon:'5'});
                                    return;
                                }
                                if(paperId===''){
                                    layer.msg("请选择试卷",{icon:'5'});
                                    return;
                                }
                                if(examStartTime==='' || examStartTime==='' ){
                                    layer.msg("请选择考试时间",{icon:'5'});
                                    return;
                                }
                                if(time==='' ){
                                    layer.msg("请输入考试所用时间（分钟）",{icon:'5'});
                                    return;
                                }

                                $.ajax({
                                    url : '/exam/save',
                                    type : 'post',
                                    contentType : 'application/json',
                                    dataType: 'json',
                                    data: JSON.stringify({
                                        "msg":"",
                                        "code":"",
                                        "data": {
                                            "title": title,
                                            "content": content,
                                            "paperId": paperId,
                                            "clazzIds": clazzs,
                                            "time": time,
                                            "examStartTime": examStartTime,
                                            "examEndTime": examEndTime
                                        }
                                    }),
                                    success : function(n) {
                                        if (n.result.status) {
                                            layer.msg("添加考试成功");
                                            layer.close(index);
                                            reload();
                                        }else {
                                            layer.msg("添加考试失败,"+n.result.msg);
                                        }
                                    },
                                    error: function(n) {
                                        layer.msg("添加考试失败,"+n.responseJSON.result.msg);
                                    }
                                });
                            },
                            end: function (res) {
                                $("#examInfoFrame").css("display", 'none');
                            }
                        });
                        break;
                }
                ;
            });

            function reload() {
                tableIns.reload({
                    where: {
                        "msg": "",
                        "code": "",
                        "data": {
                            "title": $('#search-title').val(),
                            "content": $('#search-content').val(),
                            "state": $('#search-state').val(),
                            "examStartTime": $("#search-testTime").val().split(" - ")[0],
                            "examEndTime": $("#search-testTime").val().split(" - ")[1] != null ? $("#search-testTime").val().split(" - ")[1] : "",
                            "createStartTime": $("#search-createTime").val().split(" - ")[0],
                            "createEndTime": $("#search-createTime").val().split(" - ")[1] != null ? $("#search-createTime").val().split(" - ")[1] : ""
                        }
                    }
                    , page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            }

        });

    </script>
</head>
<body>
<div class="layui-layout layui-layout-admin">

    <div th:replace="teacher/teacher-common::header"></div>
    <div th:replace="teacher/teacher-common::side('exam')"></div>

    <div class="layui-body body">
        <div class="layui-fluid" style="padding: 15px;">
            <div class="layui-card">
                <form class="layui-form layui-card-header" style="padding: 15px;min-height: 100px" lay-filter="searchexamInfoForm" id="searchexamInfoForm">
                    <div class="layui-form-item">
                        <div class="layui-inline" style="width:150px;">
                            <input class="layui-input" id="search-title" autocomplete="off" placeholder="考试名">
                        </div>
                        <div class="layui-inline" style="width:250px;">
                            <input class="layui-input" id="search-content" autocomplete="off" placeholder="内容">
                        </div>
                        <div class="layui-inline" style="margin-right: 0;">
                            <div class="layui-form-mid">状态</div>
                            <div class="layui-input-inline">
                                <select id="search-state">
                                    <option value="0">未开始</option>
                                    <option value="1">进行中</option>
                                    <option value="2">批卷中</option>
                                    <option value="3">已结束</option>
                                </select>
                            </div>
                        </div>

                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <input type="text" id="search-testTime" placeholder="考试时间" autocomplete="off" class="layui-input">
                        </div>
                        <div class="layui-inline">
                            <input type="text" id="search-createTime" placeholder="创建时间" autocomplete="off" class="layui-input">
                        </div>
                        <div class="layui-inline" style="float: right;">
                            <button type="button" class="layui-btn" id="searchBtn">
                                <i class="layui-icon layui-icon-search"></i> 搜索
                            </button>
                            <button  type="button" class="layui-btn" id="resetBtn">重置</button>
                        </div>

                    </div>
                </form>

                <div class="layui-card-body">
                    <div style="padding-bottom:10px;">
                        <table class="layui-hide" id="examTable" lay-skin="line" lay-filter="examTable">
                        </table>
                    </div>
                </div>

            </div>
        </div>

    </div>

    <div th:replace="teacher/teacher-common::footer"></div>
</div>

</body>
<div id="examInfoFrame" style="display:none;">
    <form class="layui-form" lay-filter="examInfoForm" id="examInfoForm" style="padding-right:30px">
        <div class="layui-form-item" style="margin-top: 30px">
            <label class="layui-form-label">考试名</label>
            <div class="layui-input-block">
                <input id="title" type="text" placeholder="请输入考试名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" >
            <label class="layui-form-label">描述内容</label>
            <div class="layui-input-block">
                <textarea id="content" placeholder="请输入描述内容" autocomplete="off" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item" >
            <label class="layui-form-label">选择试卷</label>
            <div class="layui-input-block" >
                <select id="paperId" lay-filter="paperId" lay-search>
                </select>
            </div>
        </div>
        <div class="layui-form-item" >
            <label class="layui-form-label">选择班级</label>
            <div class="layui-input-block" >
                <div id="clazzIds" class="xm-select-demo"></div>
            </div>
        </div>
        <div class="layui-form-item" >
            <label class="layui-form-label">考试时间</label>
            <div class="layui-input-block">
                <input type="text" id="examTime" placeholder="考试时间" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item" >
            <label class="layui-form-label">用时(分钟)</label>
            <div class="layui-input-block">
                <input type="text" id="time" placeholder="用时(分钟)" autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>
</div>
</html>